class WebServiceController < ApplicationController
  layout 'operationsmapmarker'
  require 'uri'
  require 'net/https'
  require 'open-uri'


  skip_before_filter :check_request_exception # filter the plugin installed


  def support_request  # revisar si el cliente ya existe para no crearlo de nuevo y verificar los datos.

    @error = true
    if re = request_exception
      re_name = re.name.to_s
      if re_name == "REXML::ParseException"
        xml = nil
      else
        xml = params[:support_request]
        puts "toy aki1"+xml.to_s
      end
    end
    if xml != nil    ############### desde aqui
      puts "toy aki2 "+xml.to_s
      @client = Client.find(:first, :conditions => [" account = ?", xml["client"] ])

      if @client and @client.active == 1 # si consigue al cliente(compania) y esta activo
        @address = Address.find(:first, :conditions => [" nickname = ?", xml["address"]])
        @creditcard = Creditcard.find(:first, :conditions => [" number = ?", xml["creditcard"]])

        if @address and @creditcard and @address.client_id == @client.id and @creditcard.client_id == @client.id# si se econtro la tarjeta y la direccion

          Order.transaction do # Order.transaction
            @order = Order.new(xml["order"])
            @order.client_id = @client.id
            @order.address_id = @address.id
            @order.creditcard_id = @creditcard.id
            @order.status = 0
            @order.latitude = 0
            @order.longitude = 0
            if @order.save
              @package = Package.new(xml["package"])
              @package.order_id = @order.id
              @package.price = @package.weight * 5
              if @package.save
                @package.price = @package.weight * 5
                @package.save

                @ourtotal = @package.price + ( @package.price * 0.1 )
                @error = false
              end
            end
            if @error == true
              puts "falle"
              raise ActiveRecord::Rollback
            end

          end # Order.transaction
        end # si se econtro la tarjeta y la direccion

      end   # si consigue al cliente(compania) y esta activo

    end             ############# hasta aqui es la logica del web service para recibir

    respond_to do |format|
      if @error == true
        format.xml {render :status => 500}
      else
        format.xml {render :status => :created}
      end
    end

  end


def format

    if re = request_exception
      r = re.name.to_s
      if r == "REXML::ParseException"
        #puts "fue un error de tipo " + r
      end
    end
    respond_to do |format|
      format.xml{ render :status => 200 }
    end

end

end
